#include "Camera.h"

#include <Windows.h>
#include <gl\GL.h>
#include <SDL.h>

#include "KeyManager.h"

Camera::Camera(void)
{
	mRot.identity();
	mPos.identity();
	mMat.identity();

	pitchAngle = 0.0f;
	yawAngle = 0.0f;
}

Camera::~Camera(void)
{
}

void Camera::rotate(float angle, const Vector3& axis)
{
	mRot.rotate(angle, axis);
}

void Camera::translate(const Vector3& dist)
{
	mPos.translate(-dist);
}

Vector3 Camera::getForwardVector()
{
	Vector3 dir;
	dir.set(mMat[8], mMat[9], mMat[10]);
	dir.normalize();
	return dir;
}

Vector3 Camera::getRightVector()
{
	Vector3 dir;
	dir.set(mMat[0], mMat[1], mMat[2]);
	dir.normalize();
	return dir;
}

void Camera::draw()
{
	if (KeyManager::instance()->isKeyDown(GKEY_W))
	{
		Vector3 v = getForwardVector();
		//v *= 0.2;
		translate(-v);
	}
	else if (KeyManager::instance()->isKeyDown(GKEY_S))
	{
		Vector3 v = getForwardVector();
		//v *= 0.2;
		translate(v);
	}
	
	if (KeyManager::instance()->isKeyDown(GKEY_A))
	{
		Vector3 v = getRightVector();
		v *= 0.2;
		translate(-v);
	}
	else if (KeyManager::instance()->isKeyDown(GKEY_D))
	{
		Vector3 v = getRightVector();
		v *= 0.2;
		translate(v);
	}

	mMat = mRot * mPos;
	glMultMatrixf(mMat.getTranspose());
}

void Camera::updateRotation()
{
	int midX = 320;
	int midY = 240;

	SDL_ShowCursor(SDL_DISABLE);

	int curX;
	int curY;

	SDL_GetMouseState(&curX, &curY);

	int deltaX = curX - midX;
	int deltaY = curY - midY;
	
	yawAngle += ((float)deltaX) * 0.2;
	pitchAngle += ((float)deltaY) * 0.2;

	if(pitchAngle > 80.0f)
		pitchAngle = 80.0f;
	
	if(pitchAngle < -80.0f)
		pitchAngle = -80.0f;

	if (yawAngle > 360.0)
		yawAngle -= 360.0;

	if (yawAngle < 0.0)
		yawAngle += 360.0;

	SDL_WarpMouse(midX, midY);

	mRot.identity();
	mRot.rotate(yawAngle, Vector3(0.0f, 1.0f, 0.0f));
	mRot.rotate(pitchAngle, Vector3(1.0f, 0.0f, 0.0f));

}